package cn.virens.web.components.open.wxma.config;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import cn.hutool.core.convert.Convert;

/**
 * 基于Ehcache实现微信配置缓存
 * 
 * @author virens
 */
public class WxMaCacheConfigByJCache extends AbstractWxMaCacheConfig implements InitializingBean {
	public static final String DEFAULT_CACHE_NAME = "weixin-ma-config";
	public static final String TTL = "~ttl";

	private String cacheName = DEFAULT_CACHE_NAME;

	private javax.cache.Cache<String, String> mChache;

	@Autowired
	@Qualifier("mManagerFactoryBean")
	private javax.cache.CacheManager mCacheManager;

	@Override
	protected int ttl(String key) {
		return Convert.toInt(mChache.get(key + TTL), 0);
	}

	@Override
	protected void rm(String key) {
		this.mChache.remove(key + TTL);
		this.mChache.remove(key);
	}

	@Override
	protected String get(String key) {
		return mChache.get(key);
	}

	@Override
	protected void set(String key, String value, int ttl) {
		this.mChache.put(key + TTL, Integer.toString(ttl));
		this.mChache.put(key, value);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		this.mChache = mCacheManager.getCache(cacheName, String.class, String.class);
	}

}
